package androidx.blogger.activities;

import com.google.gwt.user.client.rpc.AsyncCallback;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import androidx.blogger.BlogEntryCollectionListModel;
import androidx.blogger.BlogEntryRenderer;
import androidx.blogger.BloggerApplication;
import androidx.blogger.Log;
import androidx.blogger.R;
import androidx.blogger.tasks.DeleteBlogEntryTask;
import androidx.blogger.tasks.GetBlogEntriesTask;
import androidx.gdata.blogger.BlogEntry;
import androidx.gdata.blogger.BlogEntryCollection;
import androidx.list.ListAdapterFactory;

public class ShowUserBlog extends ConnectedActivity {
  private BlogEntryCollectionListModel blogPosts = new BlogEntryCollectionListModel();
  private Button newPostBtn;

  private static final int MENU_NEW_POST = Menu.FIRST;
  private static final int MENU_DELETE_POST = Menu.FIRST + 1;
  private static final int MENU_EDIT_POST = Menu.FIRST + 2;
  private static final int MENU_VIEW_POST = Menu.FIRST + 3;
  private static final int MENU_REFRESH = Menu.FIRST + 4;


  /** Called when the activity is first created. */
  @Override
  protected void onCreate2(Bundle savedInstanceState) {
    setContentView(R.layout.blog_posts);

    newPostBtn = (Button) findViewById(R.id.newpost_btn);
    newPostBtn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        doNewBlogPost();
      }
    });


    ListView blogEntriesList = (ListView) findViewById(R.id.userblogs_listview);
    blogEntriesList.setAdapter(ListAdapterFactory.createAdapter(this, blogPosts,
        new BlogEntryRenderer(this)));
    blogEntriesList.setOnItemClickListener(blogEntrySelectionListener);
    blogEntriesList.setOnCreateContextMenuListener(postListContextMenuListener);
    Log.i("ShowUserBlog.onCreate()");
  }

  @Override
  protected void onStart() {
  	super.onStart();
    Log.i("ShowUserBlog.onStart()");
    fetchBlogPosts();
  }

  @Override
  protected void onRestart() {
  	super.onRestart();
    Log.i("ShowUserBlog.onRestart()");
  }
  
  private void fetchBlogPosts() {
    BlogEntryCollection bec = BloggerApplication.getInstance().getBlogEntryCollection();
    if (bec != null) {
      onBlogEntriesReceived(bec);
    } else {
      GetBlogEntriesTask.execute(getProgressIndicator("Getting blog posts"), BloggerApplication
          .getInstance().getCurrentBlog(), blogEntriesCallback);
    }
  }

  private void onBlogEntriesReceived(BlogEntryCollection entries) {
    setTitle("Blog Posts on '" + BloggerApplication.getInstance().getCurrentBlog().getTitle() +"'");
    BloggerApplication.getInstance().setBlogEntryCollection(entries);
    if (entries.getBlogEntries() == null || entries.getBlogEntries().length == 0) {
      newPostBtn.setVisibility(View.VISIBLE);
    } else {
    	newPostBtn.setVisibility(View.INVISIBLE);
    }

    blogPosts.setBlogEntryCollection(entries);
  }
  
  private void onRefreshPosts() {
  	BloggerApplication.getInstance().setBlogEntryCollection(null);
  	fetchBlogPosts();
  }

  private void onBlogPostChosen(BlogEntry post) {
    Log.i("Blog post '" + post.getTitle() + "' chosen");
    BloggerApplication.getInstance().setCurrentPost(post);
    Intent intent = new Intent(this, ViewBlogPost.class);
    startActivity(intent);
  }

  private void onEditBlogPost(BlogEntry post) {
    Log.i("Blog post '" + post.getTitle() + "' chosen for edit");
    BloggerApplication.getInstance().setCurrentPost(post);
    Intent intent = new Intent(this, EditBlogPost.class);
    startActivity(intent);
  }

  private void onDeleteBlogPost(BlogEntry post) {
    Log.i("Blog post '" + post.getTitle() + "' chosen for deletion");
    DeleteBlogEntryTask.execute(getProgressIndicator("Deleting '" + post.getTitle() + "'"),
    		post, blogDeleteCallback);
  }
  
  private void onBlogPostDeleted(BlogEntry deletedpost) {
  	Log.i("Post '" + deletedpost.getTitle() + "' has been deleted");
    BloggerApplication.getInstance().setCurrentPost(null);
    BloggerApplication.getInstance().setBlogEntryCollection(null);
  	fetchBlogPosts();
  }

  private void doNewBlogPost() {
    BloggerApplication.getInstance().setCurrentPost(null);
    BloggerApplication.getInstance().setBlogEntryCollection(null);
    Intent intent = new Intent(this, EditBlogPost.class);
    //startActivityForResult(intent, 1);
    Log.i("ShowUserBlog: about to show EditBlogPost");
    startActivity(intent);
    Log.i("ShowUserBlog: startActvity for EditBlogPost finished");
//    finish();
  }
    
  private AsyncCallback<BlogEntryCollection> blogEntriesCallback =
      new AsyncCallback<BlogEntryCollection>() {
        public void onSuccess(BlogEntryCollection result) {
          onBlogEntriesReceived(result);
        }

        public void onFailure(Throwable t) {
          longMessage("Error getting blog posts");
        }
      };

  private AsyncCallback<BlogEntry> blogDeleteCallback = new AsyncCallback<BlogEntry>() {
    public void onSuccess(BlogEntry result) {
      onBlogPostDeleted(result);
    }

    public void onFailure(Throwable t) {
    	longMessage("Error deleting blog post");
    }
  };

  private OnItemClickListener blogEntrySelectionListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
      BlogEntry chosenPost = blogPosts.getItem((int) id);
      onBlogPostChosen(chosenPost);
    }
  };

  private OnCreateContextMenuListener postListContextMenuListener =
      new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
          menu.setHeaderTitle("Options");
          menu.add(0, MENU_VIEW_POST, Menu.NONE, "View Post");
          menu.add(0, MENU_EDIT_POST, Menu.NONE, "Edit Post");
          menu.add(0, MENU_DELETE_POST, Menu.NONE, "Delete Post");
        }
      };

  /** Process the context menu item selection */
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    super.onContextItemSelected(item);
    AdapterView.AdapterContextMenuInfo menuInfo =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int pos = menuInfo.position;
    BlogEntry chosenPost = blogPosts.getItem(pos);

    switch (item.getItemId()) {
      case MENU_VIEW_POST:
        onBlogPostChosen(chosenPost);
        return true;
      case MENU_EDIT_POST:
        onEditBlogPost(chosenPost);
        return true;
      case MENU_DELETE_POST:
        onDeleteBlogPost(chosenPost);
        return true;
    }
    return false;
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(Menu.NONE, MENU_NEW_POST, Menu.NONE, "New Post").setIcon(
        android.R.drawable.ic_menu_add);
    menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, "Refresh").setIcon(
        android.R.drawable.ic_menu_rotate);
    return true;
  }


  /** Process the options menu item selection */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
      case MENU_NEW_POST:
        doNewBlogPost();
        return true;
      case MENU_REFRESH:
        onRefreshPosts();
        return true;
    }
    return false;
  }

}
